<?php
// +----------------------------------------------------------------------
// | Copyright (c) 2019~2022 https://www.meoyun.com All rights reserved.
// +----------------------------------------------------------------------
// | Licensed 这不是一个自由软件，不允许对程序代码以任何形式任何目的的再发行
// +----------------------------------------------------------------------
// | Author: 喵云科技 【https://www.meoyun.com】
// +----------------------------------------------------------------------


namespace app\api\controller;

use app\common\model\Post as PostModel;
use app\common\model\Topic as TopicModel;
use app\common\service\FileService;
use app\common\service\Message;
use app\common\service\wechat\WeChatMnpService;
use app\common\validate\PostValidate;
use think\facade\Db;
use app\common\model\User as UserModel;

class Post extends BaseApi
{
    //获取帖子列表
    public function list()
    {
        $discussTitle = input("discuss_title");
        $topicId = input("topic_id");
        $classId = input("class_id");
        $topicClassId = input("topic_class_id");

        $uid = input("user_id");
        $type = input("type");

        $postKeyword = input("post_keyword");
        $userKeyword = input("user_keyword");
        $topicKeyword = input("topic_keyword");

        $where = [];

        if ($classId) {
            $where[] = ["post.class_id", "=", $classId];
        }

        if ($topicClassId) {
            $where[] = ["post.topic_class_id", "=", $topicClassId];
        }

        if ($type) {
            $where[] = ["post.type", "=", $type];
        }

        if ($discussTitle) {
            $where[] = ["discuss_list", "like", "%" . $discussTitle . "%"];
        }

        if ($topicId) {
            $where[] = ["topic_id", "=", $topicId];
        }

        if ($uid) {
            $where[] = ["post.user_id", "=", $uid];
        }

        if ($postKeyword) {
            $where[] = ["content", "like", "%" . $postKeyword . "%"];
        }

        if ($userKeyword) {
            $wUser[] = ["username", "like", "%" . $userKeyword . "%"];
            $uids = Db::name("user")->where($wUser)->column("id");
            $where[] = ["post.user_id", "in", $uids];
        }

        if ($topicKeyword) {
            $wTopic[] = ["topic_name", "like", "%" . $topicKeyword . "%"];
            $topic_ids = Db::name("topic")->where($wTopic)->column("id");
            $where[] = ["topic_id", "in", $topic_ids];
        }

        $topic = TopicModel::withJoin(["userInfo"])->where('status', 'in', [1, 2])->findOrEmpty($topicId);

        if ($topic->isEmpty()) {
            return $this->fail('圈子不存在或已关闭', 0);
        }

        $list = PostModel::getList($where);
        return $this->data($list);
    }

    //上传了图片或视频的帖子
    public function imagePost()
    {
        $where[] = ["media", "<>", "[]"];

        $topicClassId = input("topic_class_id");
        if ($topicClassId) {
            $where[] = ["post.topic_class_id", "=", $topicClassId];
        }

        $postList = PostModel::getList($where);
        return $this->data($postList);
    }

    //发布帖子
    public function release()
    {

        $params = (new PostValidate())->post()->goCheck();

        $userId = $this->getUserId();
        $user = UserModel::where('id', $userId)->findOrEmpty();

        if ($user->isEmpty()) {
            return $this->fail("登录用户不存在");
        }

        //检测账号是否可用
        if ($user->is_disable) {
            return $this->fail("您的账号异常，请联系客服。");
        }

        $checkText = (new WeChatMnpService())->msgSecCheck($user['openid'], $params["content"]);

        if (!$checkText) {
            return $this->fail('内容包含敏感文字');
        }

        $params["user_id"] = $userId;
        $params["create_time"] = time();

        $params["discuss_list"] = json_encode($params["discuss_list"], JSON_UNESCAPED_UNICODE);

        $post = PostModel::create($params);
        if ($post->id) {

            $user->post_num += 1;
            $user->exp += 5;
            $user->integral += 5;
            $user->save();

            Db::name('topic')->where('id', $params["topic_id"])->inc('post_num')->update();

            return $this->data(["id" => $post->id]);
        }

        return $this->fail('发布失败');
    }

    /**
     * [帖子详情]
     * @return [json]
     */
    public function detail()
    {

        $id = input("id");
        $userId = $this->getUserIdNoAuth();

        Db::name('post')->where('id', $id)->inc('see_num', rand(1, 20))->update();
        $postInfo = PostModel::where('id', $id)->with(["userInfo", "topicInfo"])->find();

        $postInfo["comment_count"] = Db::name("comment")->where("post_id", $id)->count();
        $postInfo["discuss_list"] = json_decode($postInfo["discuss_list"]);

        $postInfo["is_follow"] = false;
        $postInfo["is_thumb"] = false;

        if (!empty($userId)) {
            //是否已关注帖子作者
            $isFollow = Db::name("follow")->where(["user_id" => $userId, "follow_uid" => $postInfo["user_id"]])->find();
            if ($isFollow) {
                $postInfo["is_follow"] = true;
            }

            //是否已点赞帖子
            $isThumb = Db::name("post_thumb")->where(["user_id" => $userId, "post_id" => $id])->find();
            if ($isThumb) {
                $postInfo["is_thumb"] = true;
            }
        }

        return $this->data($postInfo->toArray());
    }

    //当前登录用户加入圈子的动态列表
    public function postListByjoinTopic()
    {
        $userId = $this->getUserId();
        $topicIds = Db::name("user_topic")->where("user_id", $userId)->column("topic_id");

        $where[] = ['topic_id', 'in', $topicIds];
        $postList = PostModel::getList($where);

        return $this->data($postList);
    }

    //当前登录用户发布的帖子
    public function releaseList()
    {
        $userId = $this->getUserId();
        $where["post.user_id"] = $userId;

        $list = PostModel::getList($where);
        return $this->data($list);
    }

    //用户点赞的帖子
    public function thumbList()
    {
        $userId = $this->getUserId();
        $postIds = Db::name("post_thumb")->where("user_id", $userId)->column("post_id");

        $where[] = ["post.id", "in", $postIds];
        $list = PostModel::getList($where);
        return $this->data($list);
    }

    //搜索帖子
    public function search()
    {
        $keyword = input("keyword");
        $where[] = ["content", "like", "%$keyword%"];
        $list = PostModel::getList($where);
        return $this->data($list);
    }

    //删除帖子
    public function del()
    {
        $id = input("id");
        $userId = $this->getUserId();
        $topicId = Db::name("post")->where("id", $id)->value("topic_id");
        $res = PostModel::destroy($id);
        if ($res) {
            Db::name('topic')->where('id', $topicId)->dec('post_num')->update();
            Db::name('user')->where('id', $userId)->dec('post_num')->update();
            return $this->success("删除成功");
        }

        return $this->fail("删除失败");
    }

    //点赞帖子
    public function thumbAdd()
    {
        $userId = $this->getUserId();
        $postId = input("id");
        $toUserId = input("user_id");

        $data["user_id"] = $userId;
        $data["post_id"] = $postId;

        $isCollection = Db::name("post_thumb")->where($data)->find();
        if ($isCollection) {
            return $this->fail("请勿重复点赞");
        }

        $res = Db::name("post_thumb")->insert($data);

        if ($res) {
            Db::name("post")->where("id", $postId)->inc('thumb_num')->update();
            Message::send($userId, $toUserId, $postId, 3, "点赞了您的贴子");

            return $this->success("点赞成功");
        }
        return $this->fail("点赞失败");
    }

    //取消点赞
    public function thumbCancel()
    {
        $userId = $this->getUserId();
        $postId = input("id");
        $where["user_id"] = $userId;
        $where["post_id"] = $postId;
        $res = Db::name("post_thumb")->where($where)->delete();

        if ($res) {
            Db::name("post")->where("id", $postId)->dec('thumb_num')->update();
            return $this->success("已取消点赞");
        }
        return $this->fail("取消点赞失败");
    }

//    微信检测帖子文本安全
    public function msgSecCheck()
    {
        $userId = $this->getUserId();
        $openid = Db::name("user_auth")->where('user_id', $userId)->value('openid');

        $contentTxt = input("content");

        $checkTxt = (new WeChatMnpService())->msgSecCheck($openid, $contentTxt);

        return $this->data($checkTxt);

    }

    //圈子内置顶帖子
    public function setTop()
    {
        $data = input("post.");
        $data['create_time'] = time();

        $res = Db::name("topic_top")->insert($data);
        if ($res) {
            return $this->success("置顶成功");
        }

        return $this->fail("置顶失败");
    }


    //圈子内帖子取消置顶
    public function topPostDel()
    {
        $data = input("post.");
        $res = Db::name("topic_top")->where($data)->delete();
        if ($res) {
            return $this->success();
        }

        return $this->fail();
    }

    public function checkPostImg()
    {
        $userId = $this->getUserId();
        $user = Db::name("user")->where("id", $userId)->find();

        $postId = input("post_id");

        $imgList = Db::name("post")->where("id", $postId)->value("media");
        $imgList = json_decode($imgList);


        foreach ($imgList as $imgSrc) {
            $imgSrc = FileService::getFileUrl($imgSrc);
            $checkInfoJSon = (new WeChatMnpService())->mediaCheckAsync($user["openid"], $imgSrc);
            $checkInfo = json_decode($checkInfoJSon);
            Db::name("media_check")->insert([
                'trace_id' => $checkInfo->trace_id,
                'post_id' => $postId,
                'media_src' => $imgSrc,
                'create_time' => time()
            ]);
        }

        return $this->success();
    }

    public function qrCode()
    {
        try {
            $postId = input('post_id');

            if (!is_numeric($postId)) {
                return $this->fail("非法参数");
            }

            $response = (new WeChatMnpService())->getQrCode('pages/post/detail', $postId);

            $qrcodePath = public_path() . "qrcode/post";

            if (!file_exists($qrcodePath)) {
                mkdir($qrcodePath);
            }

            $filename = "$qrcodePath/$postId.png";

            $response->saveAs($filename);

            $data = [
                'url' => request()->domain() . "/qrcode/post/$postId.png"
            ];

            return $this->data($data);
        } catch (\Throwable $e) {
            // 失败
            return $this->fail($e->getMessage());
        }
    }

    //获取待机器人推送帖子列表
    public function botPostList()
    {
        $topicId = input("topic_id");

        if (empty($topicId)) {
            return $this->fail("参数:topic_id为空");
        }

        $where[] = ["is_bot", "=", 0];
        $where[] = ["topic_id", "=", $topicId];

        $list = Db::name('post')->where($where)->field('id,content,class_id')->limit(5)->select()->toArray();

        $postList = [];
        foreach ($list as $item) {
            Db::name('post')->where("id", $item["id"])->update(["is_bot" => 1]);

		$shortLink = (new WeChatMnpService())->getShortLink('pages/post/detail?id=' .$item['id']);
		$shortLink = json_decode($shortLink);
            $postList[] = [
                "content" => $item["content"],
                "wx_link" => $shortLink->link,
                "qq_link" => 'https://q.meoyun.com/p/' . $item["id"],
                "class_name" => Db::name('topic_class')->where("id", $item["class_id"])->value('name')
            ];

        }

        return $this->data($postList);
    }
}